package org.ricks.condition2;

import java.util.function.Predicate;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public enum ComparisonOperator {
    EQUAL("==", "eq", v -> v == 0),
    NOT_EQUAL("!=", "ne", v -> v != 0),
    GREATER(">", "gt", v -> v > 0),
    LESS("<", "lt", v -> v < 0),
    GREATER_OR_EQUAL(">=", "ge", v -> v >= 0),
    LESS_OR_EQUAL("<=", "le", v -> v <= 0);

    private final Predicate<Integer> predicate;
    private final String symbol;
    private final String alias;
    private static final Map<String, ComparisonOperator> LOOKUP;

    static {
        // 通过预存储映射优化枚举查询效率
        LOOKUP = Arrays.stream(values())
                .flatMap(op -> Arrays.stream(new String[]{op.symbol, op.alias, op.name()})
                        .map(String::toLowerCase))
                .collect(Collectors.toMap(
                        key -> key,
                        key -> Arrays.stream(values())
                                .filter(op -> op.symbol.equalsIgnoreCase(key)
                                        || op.alias.equalsIgnoreCase(key)
                                        || op.name().equalsIgnoreCase(key))
                                .findFirst()
                                .orElseThrow()
                ));
    }

    ComparisonOperator(String symbol, String alias, Predicate<Integer> predicate) {
        this.symbol = symbol;
        this.alias = alias;
        this.predicate = predicate;
    }

    public static ComparisonOperator parse(String operator) {
        if (operator == null) {
            throw new IllegalArgumentException("Operator cannot be null");
        }
        String normalized = operator.trim().toLowerCase();
        ComparisonOperator op = LOOKUP.get(normalized);
        if (op == null) {
            throw new IllegalArgumentException("Unsupported operator: " + operator);
        }
        return op;
    }

    public boolean test(int comparisonResult) {
        return predicate.test(comparisonResult);
    }

    // 新增直接比较方法避免外部计算错误
    public <T extends Comparable<T>> boolean compare(T a, T b) {
        return test(a.compareTo(b));
    }

    // 获取标准符号表示
    public String getSymbol() {
        return symbol;
    }
}

